<template>
  <el-container>
    <div class="video-box">
      <video :src="src"
             :muted="false"
             :autoplay="isPlay"

             ref="video"
             :title="title"
             controls="controls"
             @touchmove.prevent
             @pause="pause"
             @play="play"
             @ended="pause"
             @loadeddata="setVideoPoster($event)"
             :style="{width:width,height:height}"
      ></video>


    </div>

  </el-container>

</template>

<script>
    export default {
        name: "VideoShow",
      props:["videoWidth","videoHeight","src"],
      data() {
          return{
            width: this.videoWidth,
            height:this.videoHeight,
            src:this.src,
            isPlay: false,
            disabled: true
          }
      },
      mounted() {
        this.$bus.$on('stopVideo',this.pause) // 子组件接受数据
      },
      beforeDestroy() {
        this.$bus.$off('stopVideo') // 销毁前清除事件监听
      },
      methods: {
        clearTimer() {
          this.timer && clearTimeout(this.timer)
        },
        play() {
          this.$bus.$emit('stopVideo') // 子组件发送数据
          this.clearTimer()
          this.isPlay = true
          // 防止点击穿透
          this.timer = setTimeout(() => {
            this.disabled = false
          }, 500)
          if (this.$refs.video) {
            this.$nextTick(() => {
              this.$refs.video.play()
            })
          }
        },
        pause() {
          this.clearTimer()
          this.isPlay = false
          this.disabled = true
        },
        setVideoPoster(event) {
          let video = event.target;
          // video.height = video.clientHeight;
          let canvas = document.createElement("canvas"); // 创建 canvas
          const ctx = canvas.getContext("2d");
          VideoShow.currentTime = 1; // 第一帧
          VideoShow.oncanplay = () => {
            canvas.width = VideoShow.clientWidth; // 获取视频宽度
            canvas.height = VideoShow.clientHeight; //获取视频高度
            var img = new Image(); // 这里使用img是为了解决视频跨域 canvas.toDataURL会提示错误的问题
            img.onload = function () {
              // canvas绘图
              ctx.drawImage(VideoShow, 0, 0, VideoShow.clientWidth, VideoShow.clientHeight);
              // 转换成base64形式并设置封面
              VideoShow.poster = canvas.toDataURL("image/jpeg", 1); // 截取后的视频封面
            }
          }
        }
      }
    }
</script>

<style scoped>

video{
  width: 100%;
  border: none;
  vertical-align: top;
  object-fit: cover;
  float: left;
  margin-right: 10px;
}
</style>
